package controllers;

import com.ning.http.util.Base64;
import models.data.*;
import models.domain.*;
import models.general.*;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.mvc.Security;
import views.html.*;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created with IntelliJ IDEA.
 * User: kristborga
 * Date: 28.2.2013
 * Time: 17:44
 * To change this template use File | Settings | File Templates.
 */
@Security.Authenticated(Secured.class)
public class TeacherController extends Controller {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm"); //to format dates
    private final static String teacherId = session().get("notandiId");
    private final static List<vKennariHoparOnn> classes = vKennariHoparOnn.getTeacherClasses(Integer.parseInt(teacherId)); //all the courses a teacher teaches this semester

    final static Form<Spurningar> questionForm = form(Spurningar.class);
    final static Form<Svor> multiChoiceForm = form(Svor.class);
    final static Form<verkefnihops> verkefniHopsForm = form(verkefnihops.class);
    final static Form<Verkefni> verkefniForm = form(Verkefni.class);
    final static Form<Verkefnaspurningar> verkefnaspurningarForm = form(Verkefnaspurningar.class);

    //Function called to show the teacher his Dashboard
    public static Result teacherDashboard() {
        String teacherID = session().get("notandiId");
        String nafn = session().get("nafn");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        List<verkefnihops> verkefniHops = verkefnihops.findProjectByTeacher(teacherID);  //get all the projects the teacher has created for its groups on the current semester
        List<Project> projects = new ArrayList<Project>();

        for(verkefnihops single:verkefniHops)   {

            Double grade = 10.0;
            Date lokadagsetning = single.lokadagsetning;
            Date upphafsdagsetning = single.upphafsdagsetning;
            Date today = new Date();
            //only projects that can still be turned in are shown on this dashboard (has to go into assignments to get the assignments that are closed)
            if(today.before(lokadagsetning)){
                String loka = simpleDateFormat.format(lokadagsetning);
                String upphafs = simpleDateFormat.format(upphafsdagsetning);
                Afangar afangi = Afangar.getAfangi(single.afangi_id);
                Verkefni verkefni = Verkefni.findProjectByVerkefniID(single.verkefni_id); //used to get the name of the project

                if(verkefni.tegund.equals("verkefni")){
                    projects.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,false,upphafs,loka,"project",verkefni.verkefni_id,lokadagsetning,single.getHopur_id()));
                }
                else if(verkefni.tegund.equals("prof")){
                    projects.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,false,upphafs,loka,"test",verkefni.verkefni_id,lokadagsetning,single.getHopur_id()));
                }
            }
        }

        List<TimetableHomework> monday = new ArrayList<TimetableHomework>();
        List<TimetableHomework> tuesday = new ArrayList<TimetableHomework>();
        List<TimetableHomework> wednesday = new ArrayList<TimetableHomework>();
        List<TimetableHomework> thursday = new ArrayList<TimetableHomework>();
        List<TimetableHomework> friday = new ArrayList<TimetableHomework>();

        List<List<Stundatoflur_NK>> stundatafla = Stundatoflur_NK.getStundataflaKennara(classes);  //List that has a seperate list for the course schedule each day
        List<List<Heimavinna>> heimavinna = Heimavinna.getTeacherHomeworkWeek(classes);  //List that has a seperate list for the homework each day
        List<TimetableHomework> All = TimetableHomework.makeTimetableHomework(stundatafla, heimavinna);

        for (TimetableHomework dagur : All) {
            if(dagur.getDagur().equals("manudagur")){
                monday.add(dagur);
            }
            if(dagur.getDagur().equals("thridjudagur")){
                tuesday.add(dagur);
            }
            if(dagur.getDagur().equals("midvikudagur")){
                wednesday.add(dagur);
            }
            if(dagur.getDagur().equals("fimmtudagur")){
                thursday.add(dagur);
            }
            if(dagur.getDagur().equals("fostudagur")){
                friday.add(dagur);
            }

        }

        List<Tilkynning> tilkynningList = Tilkynning.getTeacherTopFiveAnnouncements(classes); //get top five announcements relevant to the teacher that is logged in
        List<Announcements> announcements = Announcements.createAnnouncementList(tilkynningList);
        List<Athugasemdir> athugasemdir = Athugasemdir.getTeacherFiveNewestComments(teacherID);
        List<Comments> newerComments = Comments.createCommentList(athugasemdir); //get the newest comments to display on the dashboard
        projects = CommonController.sortProjectsByDate(projects);
        //only want to show the teacher five projects on his dashboard
        List<Project> displayProjects = new ArrayList<Project>();
        if(projects.size() > 5){
            for(int i = 0; i < 5 ; i++){
                displayProjects.add(projects.get(i));
            }
        }
        else{
            for(int i = 0; i< projects.size(); i++){
                displayProjects.add(projects.get(i));
            }
        }

        return ok(teacherDashboard.render(displayProjects, announcements, classes,newerComments,monday,tuesday, wednesday, thursday,friday, nafn));
    }

    public static boolean isTeacher(String userId){
        if(Notendur.checkIfStudent(userId)){
            return false;
        }
        else
            return true;
    }

    //Function called when the teacher wants to create a question
    public static Result createQuestion(int verkefniId) {
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        //return ok(createQuestion.render(questionForm, classes, multiChoiceForm,  Leitarskilyrdi.getAllLeitarskilyrdi()));

        List<vAfangarBaekur> allBooksForTeacher = vAfangarBaekur.getAllBooksByAfangarId(classes);
        List<StringIntegerClass> test = new ArrayList<StringIntegerClass>();
        for(int j=0;j<allBooksForTeacher.size();j++){
            StringIntegerClass stringIntegerClass=new StringIntegerClass(allBooksForTeacher.get(j).getHeiti(),allBooksForTeacher.get(j).getBok_id());
            test.add(stringIntegerClass);
        }
        HashSet<StringIntegerClass> noDuplicates = new HashSet<StringIntegerClass>(test);
        List<StringIntegerClass> noDups = new ArrayList<StringIntegerClass>(noDuplicates);

        //direct the teacher to the CreateQuestion view
        return ok(createQuestion.render(questionForm, classes, multiChoiceForm,  Leitarskilyrdi.getAllLeitarskilyrdi(), noDups, verkefniId));
    }

    //Used to show the exams the teacher has created for some of his group/groups
    public static Result teacherExams(){
        String teacherID = session().get("notandiId");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }

        List<verkefnihops> verkefniHops = verkefnihops.findProjectByTeacher(teacherID);
        List<Verkefni> verk = Verkefni.findProjectByTeacherID(teacherID);
        List<Project> tempProjects = new ArrayList<Project>();

        if (verkefniHops.size() > 0){
            for (verkefnihops vhop : verkefniHops) {
                Verkefni tempverkefni = Verkefni.findProjectByVerkefniID(vhop.verkefni_id);
                tempProjects.add(new Project(tempverkefni.getHeiti(),tempverkefni.getVaegi(),tempverkefni.getTegund(),tempverkefni.verkefni_id, Integer.parseInt(tempverkefni.getAfangi_id())));
            }
        }
        List<Project> openExams = new ArrayList<Project>();
        List<Project> closedExams = new ArrayList<Project>();
        List<Project> oldExams = new ArrayList<Project>();

        if (verk.size() > 0){  //exams that haven't been published
            for(Verkefni single:verk){
                if(!verkefnihops.hasProjectBeenSchedualed(single.verkefni_id)){
                    if(single.getTegund().equals("prof")){
                        Afangar afangi = Afangar.getAfangi(Integer.toString(Integer.parseInt(single.getAfangi_id())));
                        oldExams.add(new Project(single.getHeiti(), 0.0, single.getVaegi(), afangi.namsgrein_afanganr, false, "test", single.getVerkefni_id()));
                    }
                }

            }
        }

        Double grade = 0.0;
        String lokaOpen = new String();
        String lokaClosed = new String();
        //Get the openExams (deadline has not passed), and closedExams(deadline has passed)
        for(verkefnihops single:verkefniHops){
            Date lokadagsetning = new Date();
            Date upphafsdagsetning = new Date();
            lokadagsetning = single.lokadagsetning;
            upphafsdagsetning = single.upphafsdagsetning;
            Date today = new Date();
            if (today.before(lokadagsetning)) {
                lokaOpen = simpleDateFormat.format(lokadagsetning);
            } else {
                lokaClosed = simpleDateFormat.format(lokadagsetning);
            }
            String upphafs = simpleDateFormat.format(upphafsdagsetning);
            Afangar afangi = Afangar.getAfangi(single.afangi_id);
            Verkefni verk1 = Verkefni.findProjectByVerkefniID(single.verkefni_id);

            if (verk1.tegund.equals("prof") && today.before(lokadagsetning)) {
                openExams.add(new Project(verk1.heiti, grade, verk1.vaegi, afangi.namsgrein_afanganr, false, upphafs, lokaOpen, "test", verk1.verkefni_id,single.getHopur_id(),lokadagsetning));
            } else if (verk1.tegund.equals("prof") && today.after(lokadagsetning)) {
                closedExams.add(new Project(verk1.heiti, grade, verk1.vaegi, afangi.namsgrein_afanganr, false, upphafs, lokaClosed, "test", verk1.verkefni_id,single.getHopur_id(),lokadagsetning));
            }
        }
        openExams = CommonController.sortProjectsByDate(openExams);
        closedExams = CommonController.sortProjectsByDate(closedExams);
        return ok(teacherExams.render(openExams, closedExams,oldExams));
    }

    // <editor-fold desc="CREATE QUESTION">
    //Save a single choice question the teacher just created
    public static Result saveSingleChoice(int verkefniId){
        List<vAfangarBaekur> allBooksForTeacher = vAfangarBaekur.getAllBooksByAfangarId(classes);
        List<StringIntegerClass> test = new ArrayList<StringIntegerClass>();
        for(int j=0;j<allBooksForTeacher.size();j++){
            StringIntegerClass stringIntegerClass=new StringIntegerClass(allBooksForTeacher.get(j).getHeiti(),allBooksForTeacher.get(j).getBok_id());
            test.add(stringIntegerClass);
        }
        Set<StringIntegerClass> noDuplicates = new HashSet<StringIntegerClass>(test);
        test.clear();
        test.addAll(noDuplicates);

        int rettsvar = 0;

        Form<Spurningar> filledForm = questionForm.bindFromRequest();
        if (filledForm.hasErrors()) {
            return badRequest(createQuestion.render(questionForm, classes, multiChoiceForm,  Leitarskilyrdi.getAllLeitarskilyrdi(),test, verkefniId));
        }
        else {
            String teacherId =session().get("notandiId");
            Date date = new Date();
            Annir onn = Annir.returnOnn();
            String bok_id = filledForm.get().bok_id;
            //if intBok_id = 0, then the question isn't from a book
            Integer intBok_id = 0;
            List<vAfangarBaekur> bok = new ArrayList<vAfangarBaekur>();
            String bokHeiti = "";
            if(!bok_id.equals("noBook")){
                intBok_id = Integer.parseInt(bok_id);
                bok = vAfangarBaekur.getBokFromId(intBok_id);
                bokHeiti = bok.get(0).getHeiti();
            }

            String afangi_id = filledForm.get().afangi_id;

            //kafli,nr_utgafu, hofundur_bokar is empty because we expect that all the books taught in the courses are registered in the table bokalisti
            Spurningar spurning = Spurningar.create("krossar", filledForm.get().texti, onn.onn_id, afangi_id,
                    filledForm.get().tyngdarstig, teacherId, bok_id, "",
                    "", "", filledForm.get().vidhengi,bokHeiti);

            //Get the tags and save them
            String[] leitarskilyrdi = request().body().asFormUrlEncoded().get("spurningLeitarskilyrdi");
            if (leitarskilyrdi != null){
                for (int i = 0; i < leitarskilyrdi.length; i++) {
                    String tag = leitarskilyrdi[i];
                    if (tag != null && !tag.isEmpty()) {
                        Leitarskilyrdi savedLeitarskilyrdi = Leitarskilyrdi.create(tag,filledForm.get().afangi_id);
                        Spurningar_leitarskilyrdi.create(savedLeitarskilyrdi.leitarskilyrdi_id, spurning.spurningar_id, filledForm.get().afangi_id);
                    }
                }
            }

            String[] questionOption = request().body().asFormUrlEncoded().get("svor_texti");
            List<Svor> svor = new ArrayList<Svor>();
            if (questionOption != null) {
                for (int i = 0; i < questionOption.length; i++) {
                    String option = questionOption[i];
                    if(i == 0){
                        rettsvar = 1;  //The first answer is the correct one
                    }
                    else{
                        rettsvar = 0;
                    }
                    svor.add(new Svor(spurning.getSpurningar_id(), option, teacherId, teacherId, rettsvar));

            }
            }
            //Because the first answer is the correct one we shuffle them.
            Collections.shuffle(svor);
            for(Svor s : svor){
                Svor.create(s.getSpurning_id(), s.getTexti(), s.getPerson_create(), s.getPerson_edit(), s.getRettsvar());
            }
            if(verkefniId == 0){
                return redirect(routes.TeacherController.createQuestion(verkefniId));
            }else{
                return redirect(routes.TeacherController.questionToAssignment(verkefniId));
            }
        }
    }

    //Save a multi choice question the teacher just created
    public static Result saveMultiChoice(int verkefniId) {
         Form<Spurningar> filledForm = questionForm.bindFromRequest();
        List<vAfangarBaekur> allBooksForTeacher = vAfangarBaekur.getAllBooksByAfangarId(classes);
        List<StringIntegerClass> test = new ArrayList<StringIntegerClass>();
        for(int j=0;j<allBooksForTeacher.size();j++){
            StringIntegerClass stringIntegerClass=new StringIntegerClass(allBooksForTeacher.get(j).getHeiti(),allBooksForTeacher.get(j).getBok_id());
            test.add(stringIntegerClass);
        }
        Set<StringIntegerClass> noDuplicates = new HashSet<StringIntegerClass>(test);
        test.clear();
        test.addAll(noDuplicates);

            if (filledForm.hasErrors()) {
                return badRequest(createQuestion.render(questionForm, classes, multiChoiceForm,  Leitarskilyrdi.getAllLeitarskilyrdi(), test, verkefniId));
            }
            else {
                String teacherId =session().get("notandiId");
                int rettsvar = 1;
                Date date = new Date();
                Annir onn = Annir.returnOnn();
                String bok_id = filledForm.get().bok_id;
                //if intBok_id = 0, then the question isn't from a book
                Integer intBok_id = 0;
                List<vAfangarBaekur> bok = new ArrayList<vAfangarBaekur>();
                String bokHeiti = "";
                if(!bok_id.equals("noBook")){
                    intBok_id = Integer.parseInt(bok_id);
                    bok = vAfangarBaekur.getBokFromId(intBok_id);
                    bokHeiti = bok.get(0).getHeiti();
                }
                String afangi_id = filledForm.get().afangi_id;


                //kafli,nr_utgafu, hofundur_bokar is empty because we expect that all the books taught in the courses are registered in the table bokalisti
                Spurningar spurning = Spurningar.create("fjolval", filledForm.get().texti, onn.onn_id, afangi_id,
                filledForm.get().tyngdarstig, teacherId, bok_id, "",
                "", "", filledForm.get().vidhengi,bokHeiti);                 //Save the question

                String[] questionOption = request().body().asFormUrlEncoded().get("svor_texti");
                String[] rightOrWrong = request().body().asFormUrlEncoded().get("rettsvar");

                if (questionOption != null) {      //Go through all the answers and if it is correct we put 1 and if it is wrong we put 0
                    for (int i = 0; i < questionOption.length; i++) {
                        String option = questionOption[i];
                        if(rightOrWrong[i].equals("rett")) {
                            rettsvar = 1;
                        }
                        else{
                            rettsvar = 0;
                        }
                        Svor.create(spurning.getSpurningar_id(), option, teacherId, teacherId, rettsvar);
                    }//end of for sentence
                }//end of if(questionOption != null)

                String[] leitarskilyrdi = request().body().asFormUrlEncoded().get("spurningLeitarskilyrdi");//Save the tags
                if (leitarskilyrdi != null){
                    for (int i = 0; i < leitarskilyrdi.length; i++) {
                    String tag = leitarskilyrdi[i];
                        if (tag != null && !tag.isEmpty()) {
                            Leitarskilyrdi savedLeitarskilyrdi = Leitarskilyrdi.create(tag,filledForm.get().afangi_id);
                            Spurningar_leitarskilyrdi.create(savedLeitarskilyrdi.leitarskilyrdi_id, spurning.spurningar_id, filledForm.get().afangi_id);
                        }
                    }
                }

                if(verkefniId == 0){
                    return redirect(routes.TeacherController.createQuestion(verkefniId));
                }else{
                    return redirect(routes.TeacherController.questionToAssignment(verkefniId));
                }
            }
    }

    //Saves a text question to database that the teacher just created
    public static Result validateQuestion(int verkefniId){//} throws SQLException {
        Form<Spurningar> filledForm = questionForm.bindFromRequest();
            if (filledForm.hasErrors()) {

                List<vAfangarBaekur> allBooksForTeacher = vAfangarBaekur.getAllBooksByAfangarId(classes);
                List<StringIntegerClass> test = new ArrayList<StringIntegerClass>();
                for(int j=0;j<allBooksForTeacher.size();j++){
                    StringIntegerClass stringIntegerClass=new StringIntegerClass(allBooksForTeacher.get(j).getHeiti(),allBooksForTeacher.get(j).getBok_id());
                    test.add(stringIntegerClass);
                }
                Set<StringIntegerClass> noDuplicates = new HashSet<StringIntegerClass>(test);
                test.clear();
                test.addAll(noDuplicates);

                return badRequest(createQuestion.render(questionForm, classes, multiChoiceForm,  Leitarskilyrdi.getAllLeitarskilyrdi(),test, verkefniId));
            } else {
                String teacherId =session().get("notandiId");
                Annir onn = Annir.returnOnn();
                String afangi_id = filledForm.get().afangi_id;

                String bok_id = filledForm.get().bok_id;
                //if intBok_id = 0, then the question isn't from a book
                Integer intBok_id = 0;
                List<vAfangarBaekur> bok = new ArrayList<vAfangarBaekur>();
                String bokHeiti = "";
                if(!bok_id.equals("noBook")){
                    intBok_id = Integer.parseInt(bok_id);
                    bok = vAfangarBaekur.getBokFromId(intBok_id);
                    bokHeiti = bok.get(0).getHeiti();
                }

                //kafli,nr_utgafu, hofundur_bokar is empty because we expect that all the books taught in the courses are registered in the table bokalisti
                Spurningar spurning = Spurningar.createTextQuesitonWOAttachment(filledForm.get().tegund, filledForm.get().texti, onn.onn_id, afangi_id, filledForm.get().tyngdarstig, teacherId, bok_id, "", "", "",bokHeiti);

                String[] leitarskilyrdi = request().body().asFormUrlEncoded().get("spurningLeitarskilyrdi"); //Add the tags
                if (leitarskilyrdi != null){
                    for (int i = 0; i < leitarskilyrdi.length; i++) {
                    String tag = leitarskilyrdi[i];
                        if (tag != null && !tag.isEmpty()) {
                            Leitarskilyrdi savedLeitarskilyrdi = Leitarskilyrdi.create(tag,afangi_id);
                            Spurningar_leitarskilyrdi.create(savedLeitarskilyrdi.leitarskilyrdi_id, spurning.spurningar_id, afangi_id);
                        }
                    }
                }

            if(verkefniId == 0){
                    return redirect(routes.TeacherController.createQuestion(verkefniId));
                }else{
                    return redirect(routes.TeacherController.questionToAssignment(verkefniId));
                }
            }

    }

    //Saves a sentence completion question that the teacher just created
    public static Result submitEydufylling(int verkefniId) {
        Form<Spurningar> filledForm = questionForm.bindFromRequest();
        if (filledForm.hasErrors()) {
            List<vAfangarBaekur> allBooksForTeacher = vAfangarBaekur.getAllBooksByAfangarId(classes);
            List<StringIntegerClass> test = new ArrayList<StringIntegerClass>();
            for(int j=0;j<allBooksForTeacher.size();j++){
                StringIntegerClass stringIntegerClass=new StringIntegerClass(allBooksForTeacher.get(j).getHeiti(),allBooksForTeacher.get(j).getBok_id());
                test.add(stringIntegerClass);
            }
            Set<StringIntegerClass> noDuplicates = new HashSet<StringIntegerClass>(test);
            test.clear();
            test.addAll(noDuplicates);

            return badRequest(createQuestion.render(questionForm, classes, multiChoiceForm, Leitarskilyrdi.getAllLeitarskilyrdi(),test, verkefniId));
        } else {
            String teacherId =session().get("notandiId");
            Annir onn = Annir.returnOnn();

            String[] postAction = request().body().asFormUrlEncoded().get("texti");
            String[] lysing = request().body().asFormUrlEncoded().get("eyduLysing");
            String texti = postAction[0];
            String lysingSpurningar = lysing[0];
            String afangi_id=filledForm.get().afangi_id;

            String bok_id = filledForm.get().bok_id;//body.asFormUrlEncoded().get("book_id");
            //if intBok_id = 0, then the question isn't from a book
            Integer intBok_id = 0;
            List<vAfangarBaekur> bok = new ArrayList<vAfangarBaekur>();
            String bokHeiti = "";
            if(!bok_id.equals("noBook")){
                intBok_id = Integer.parseInt(bok_id);
                bok = vAfangarBaekur.getBokFromId(intBok_id);
                bokHeiti = bok.get(0).getHeiti();
            }

            //kafli,nr_utgafu, hofundur_bokar is empty because we expect that all the books taught in the courses are registered in the table bokalisti
            Spurningar spurning = Spurningar.createWithoutVidhengi("eydufylling", lysingSpurningar, onn.onn_id,afangi_id,filledForm.get().tyngdarstig,
                    teacherId, bok_id, "", "", "",bokHeiti);
            Svor svor = Svor.createEydufylling(spurning.getSpurningar_id(), texti, teacherId);

            String[] leitarskilyrdi = request().body().asFormUrlEncoded().get("spurningLeitarskilyrdi");
            if(leitarskilyrdi != null){
                for (int i = 0; i < leitarskilyrdi.length; i++) {
                    String tag = leitarskilyrdi[i];
                    if (tag != null && !tag.isEmpty()) {
                        Leitarskilyrdi savedLeitarskilyrdi = Leitarskilyrdi.create(tag,filledForm.get().afangi_id);
                        Spurningar_leitarskilyrdi.create(savedLeitarskilyrdi.leitarskilyrdi_id, spurning.spurningar_id, filledForm.get().afangi_id);
                    }
                }
            }

            if(verkefniId == 0){
                return redirect(routes.TeacherController.createQuestion(verkefniId));
            }else{
                return redirect(routes.TeacherController.questionToAssignment(verkefniId));
            }
        }
    }

    //Saves a picture question that the teacher just created
    public static Result submitPicture(int verkefniId) throws SQLException, ParseException {
        Form<Spurningar> filledForm = questionForm.bindFromRequest();
        Http.MultipartFormData body = request().body().asMultipartFormData();
        Http.MultipartFormData.FilePart vidhengi = body.getFile("vidhengi");
        try{
            List<vAfangarBaekur> allBooksForTeacher = vAfangarBaekur.getAllBooksByAfangarId(classes);
            List<StringIntegerClass> test = new ArrayList<StringIntegerClass>();
            for(int j=0;j<allBooksForTeacher.size();j++){
                StringIntegerClass stringIntegerClass=new StringIntegerClass(allBooksForTeacher.get(j).getHeiti(),allBooksForTeacher.get(j).getBok_id());
                test.add(stringIntegerClass);
            }
            Set<StringIntegerClass> noDuplicates = new HashSet<StringIntegerClass>(test);
            test.clear();
            test.addAll(noDuplicates);

            if (filledForm.hasErrors()) {
                return badRequest(createQuestion.render(questionForm, classes, multiChoiceForm,  Leitarskilyrdi.getAllLeitarskilyrdi(),test, verkefniId));
            }
            else {
                String teacherId =session().get("notandiId");
                Annir onn = Annir.returnOnn();

                String[] postAction = body.asFormUrlEncoded().get("texti");
                String texti = postAction[0];

                String afangi_id=filledForm.get().afangi_id;

                String bok_id = filledForm.get().bok_id;//body.asFormUrlEncoded().get("book_id");
                //if intBok_id = 0, then the question isn't from a book
                Integer intBok_id = 0;
                List<vAfangarBaekur> bok = new ArrayList<vAfangarBaekur>();
                String bokHeiti = "";
                if(!bok_id.equals("noBook")){
                    intBok_id = Integer.parseInt(bok_id);
                    bok = vAfangarBaekur.getBokFromId(intBok_id);
                    bokHeiti = bok.get(0).getHeiti();
                }


                //kafli,nr_utgafu, hofundur_bokar is empty because we expect that all the books taught in the courses are registered in the table bokalisti
                Spurningar spurning = Spurningar.createWithoutVidhengi("mynd", texti, onn.onn_id, afangi_id,filledForm.get().tyngdarstig,
                        teacherId, bok_id, "","","",bokHeiti);

                Vidhengitafla.create(spurning.spurningar_id, vidhengi.getFilename(), vidhengi.getFile(), spurning.kennari_id,vidhengi.getContentType());

                String[] leitarskilyrdi = body.asFormUrlEncoded().get("spurningLeitarskilyrdi");
                if(leitarskilyrdi != null){
                    for (int i = 0; i < leitarskilyrdi.length; i++) {
                        String tag = leitarskilyrdi[i];
                        if (tag != null && !tag.isEmpty()) {
                            Leitarskilyrdi savedLeitarskilyrdi = Leitarskilyrdi.create(tag,filledForm.get().afangi_id);
                            Spurningar_leitarskilyrdi.create(savedLeitarskilyrdi.leitarskilyrdi_id, spurning.spurningar_id, filledForm.get().afangi_id);
                        }
                    }
                }
            if(verkefniId == 0){
                    return redirect(routes.TeacherController.createQuestion(verkefniId));
                }else{
                    return redirect(routes.TeacherController.questionToAssignment(verkefniId));
                }
            }
        } // end of try
        catch (SQLException e) {
            return redirect(routes.TeacherController.teacherDashboard());
        }
    }

    //Saves an attachment question to the database that the teacher just created
    public static Result addVidhengiQuestion(int verkefniId) throws SQLException {
        try {
                String teacherId =session().get("notandiId");
                Annir onn = Annir.returnOnn();

                Http.MultipartFormData body = request().body().asMultipartFormData();
                Http.MultipartFormData.FilePart vidhengi = body.getFile("vidhengi"); //get the attachment

                String[] bok_id = body.asFormUrlEncoded().get("bok_id");
                List<vAfangarBaekur> bok = new ArrayList<vAfangarBaekur>();
                String bokHeiti = "";
                //if intBok_id = 0, then the question isn't from a book
                Integer intBok_id = 0;
                if(!bok_id[0].equals("noBook")){
                    intBok_id = Integer.parseInt(bok_id[0]);
                    bok = vAfangarBaekur.getBokFromId(intBok_id);
                    bokHeiti = bok.get(0).getHeiti();
                }

                String[] afangi = body.asFormUrlEncoded().get("afangi_id");
                String afangi_id = afangi[0];

            //if tyngdarstig=0, then the field has not been filled
            //bok_id, kafli, nr_utgafu, hofundurbokar = empty string, then these fields will not have been filled out
            Spurningar spurning = Spurningar.create("vidhengi", vidhengi.getFilename(), onn.onn_id, afangi_id, 0, teacherId, bok_id[0], "","","",vidhengi,bokHeiti);

                String[] leitarskilyrdi = body.asFormUrlEncoded().get("spurningLeitarskilyrdi");
                if (leitarskilyrdi != null){
                    for (int i = 0; i < leitarskilyrdi.length; i++) {
                        String tag = leitarskilyrdi[i];
                        if (tag != null && !tag.isEmpty()) {
                            Leitarskilyrdi savedLeitarskilyrdi = Leitarskilyrdi.create(tag,afangi_id);
                            Spurningar_leitarskilyrdi.create(savedLeitarskilyrdi.leitarskilyrdi_id, spurning.spurningar_id, afangi_id);
                        }
                    }
                }

                if (vidhengi != null) {
                    Vidhengitafla.create(spurning.spurningar_id, vidhengi.getFilename(), vidhengi.getFile(), spurning.kennari_id, vidhengi.getContentType());
                }
        if(verkefniId == 0){
                return redirect(routes.TeacherController.createQuestion(verkefniId));
            }else{
                return redirect(routes.TeacherController.questionToAssignment(verkefniId));
            }
        }
        catch (SQLException e) {
            return redirect(routes.TeacherController.teacherDashboard());
        }
    }

    // <editor-fold desc="FÖLL FYRIR VERKEFNI">

    public static Result createAssignment() {
        String teacherId = session().get("notandiId");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        int onnId = classes.get(0).getOnn_id();
        return ok(createAssignment.render(verkefniForm, classes, teacherId, onnId));
    }

    //save to database the assignment the teacher just created
    public static Result submitAssignment() {
        Form<Verkefni> filledForm = verkefniForm.bindFromRequest();
        String teacherId = session().get("notandiId");
        if (filledForm.hasErrors()) {
            int onnId = classes.get(0).getOnn_id();
            return badRequest(createAssignment.render(filledForm, classes, teacherId, onnId));
        } else {
            Verkefni verkefni = Verkefni.create(filledForm.get().heiti, filledForm.get().kennari_id, filledForm.get().tegund, filledForm.get().afangi_id, filledForm.get().onn_id, filledForm.get().vaegi);
            return redirect(routes.TeacherController.questionToAssignment(verkefni.verkefni_id));
        }
    }

    //Saves a question to database and redirect teacher to assignmentQuestion view
    public static Result QuestionFromAssignment(int verkefniId) {
        Form<Spurningar> filledForm = questionForm.bindFromRequest();

        String bok_id = filledForm.get().bok_id;
        Integer intBok_id = Integer.parseInt(bok_id);
        String afangi_id=filledForm.get().afangi_id;
        List<vAfangarBaekur> bok = vAfangarBaekur.getBokFromId(intBok_id);

        List<vAfangarBaekur> allBooksForTeacher = vAfangarBaekur.getAllBooksByAfangarId(classes);
        List<StringIntegerClass> test = new ArrayList<StringIntegerClass>();
        for(int j=0;j<allBooksForTeacher.size();j++){
            StringIntegerClass stringIntegerClass=new StringIntegerClass(allBooksForTeacher.get(j).getHeiti(),allBooksForTeacher.get(j).getBok_id());
            test.add(stringIntegerClass);
        }
        Set<StringIntegerClass> noDuplicates = new HashSet<StringIntegerClass>(test);
        test.clear();
        test.addAll(noDuplicates);

        if (filledForm.hasErrors()) {
            return badRequest(createQuestion.render(questionForm,classes, multiChoiceForm,  Leitarskilyrdi.getAllLeitarskilyrdi(),test, verkefniId));
        } else {
            String teacherId = session().get("notandiId");  //
            Spurningar.create(filledForm.get().tegund, filledForm.get().texti, filledForm.get().onn_id,
                    afangi_id, filledForm.get().tyngdarstig,
                    teacherId, filledForm.get().bok_id, "",
                    "", "", filledForm.get().vidhengi,bok.get(0).getHeiti());
            return redirect(routes.TeacherController.questionToAssignment(verkefniId));
        }
    }

    //Displays questions you can select for a project
    public static Result questionToAssignment(int verkefniId) {
        String notandiID = session().get("notandiId");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        Verkefni verkefni = Verkefni.find.byId(verkefniId);

        List<Spurningar> spurningar = Spurningar.findAllSpurningarByAfangiList(classes);//findByAfangiId(verkefni.getAfangi_id());

        List<Spurningar_leitarskilyrdi> sp_leit = new ArrayList<Spurningar_leitarskilyrdi>();
        if(Spurningar_leitarskilyrdi.getAllSpurningar_leitarskilyrdi() != null){
            sp_leit = Spurningar_leitarskilyrdi.getAllSpurningar_leitarskilyrdi();
        }


        List<Question> questions = new ArrayList<Question>();

        for(Spurningar spurning : spurningar){
            String dagurbuidtil = simpleDateFormat.format(spurning.dagurstofnad);

            List<Leitarskilyrdi> tags = new ArrayList<Leitarskilyrdi>();
            for(Spurningar_leitarskilyrdi spurn : sp_leit){
                if(spurning.spurningar_id.equals(spurn.spurning_id)){
                    tags.add(Leitarskilyrdi.findById(spurn.leitarskilyrdi_id));
                }
            }
            String namsgr_afanganr = getAfangiNamsgrein(Integer.parseInt(spurning.afangi_id));

            //String namsgr_afanganr = getAfangiNamsgrein(Integer.parseInt(spurning.afangi_id));
            questions.add(new Question(spurning.spurningar_id,spurning.tegund,spurning.onn_id, spurning.texti, spurning.afangi_id,spurning.tyngdarstig,
                    spurning.kennari_id,spurning.kafli,spurning.vidhengi,spurning.nr_utgafu,spurning.hofundur_bokar,dagurbuidtil, tags,spurning.bok_nafn,namsgr_afanganr));

        }
        return ok(AssignmentQuestions.render(verkefni.verkefni_id, verkefni.vaegi, questions, verkefnaspurningarForm, questionForm, classes , Annir.fillSemesterList(notandiID),verkefni.getHeiti()));
    }

    //Föll sem setja spurningar í verkefni
    public static Result putQuestionToAssignment() {
        Form<Verkefnaspurningar> verkefnaspurningarForm = form(Verkefnaspurningar.class).bindFromRequest();
        if (verkefnaspurningarForm.hasErrors()) {
            flash("success", "Villa kom upp");
            return redirect(routes.TeacherController.createAssignment());
        } else {
            String[] postAction = request().body().asFormUrlEncoded().get("spurningar_id");    //get all checked questions
            if (postAction != null) {
                Double vaegi = verkefnaspurningarForm.get().vaegi;
                int verkefniId = verkefnaspurningarForm.get().verkefni_id;
                for (int i = 0; i < postAction.length; i++) {
                    String spurningarID = postAction[i];
                    Verkefnaspurningar verkefnaspurningar = Verkefnaspurningar.create(verkefniId, Integer.parseInt(spurningarID), vaegi);
                }
            }
            return redirect(routes.TeacherController.assignmentToGroups(verkefnaspurningarForm.get().verkefni_id));
        }
    }

    //VIEW TEACHERASSIGNMENTS
    public static Result teacherAssignments() {
        String teacherID = session().get("notandiId");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }

        List<verkefnihops> verkefniHops = verkefnihops.findProjectByTeacher(teacherID);
        List<Verkefni> verk = Verkefni.findProjectByTeacherID(teacherID);
        List<Project> tempProjects = new ArrayList<Project>();
        List<Project> oldAssignments = new ArrayList<Project>();
        /*if (verkefniHops.size() > 0){
            for (Verkefni tempverkefni : verk) {
                if(tempverkefni.getTegund().equals("verkefni")){
                    tempProjects.add(new Project(tempverkefni.getHeiti(),tempverkefni.getVaegi(),tempverkefni.getTegund(),tempverkefni.verkefni_id, Integer.parseInt(tempverkefni.getAfangi_id())));
                }
            }
        }    */
        List<Project> openProjects = new ArrayList<Project>();
        List<Project> closedProjects = new ArrayList<Project>();

        //Get all the assignments that haven't been used.
        if (verk.size() > 0){
            for(Verkefni single:verk){
                if(!verkefnihops.hasProjectBeenSchedualed(single.verkefni_id)){
                    if(single.getTegund().equals("verkefni")){
                        Afangar afangi = Afangar.getAfangi(Integer.toString(Integer.parseInt(single.getAfangi_id())));
                        oldAssignments.add(new Project(single.getHeiti(), 0.0, single.getVaegi(), afangi.namsgrein_afanganr, false, "assignment", single.getVerkefni_id()));
                    }
                }

            }
        }



        Double grade = 0.0;
        String lokaOpen = new String();
        String lokaClosed = new String();

        for(verkefnihops single:verkefniHops){
            Date lokadagsetning = new Date();
            Date upphafsdagsetning = new Date();
            lokadagsetning = single.lokadagsetning;
            upphafsdagsetning = single.upphafsdagsetning;
            Date today = new Date();
            if (today.before(lokadagsetning)) {
                lokaOpen = simpleDateFormat.format(lokadagsetning);
            } else {
                lokaClosed = simpleDateFormat.format(lokadagsetning);
            }
            String upphafs = simpleDateFormat.format(upphafsdagsetning);
            Afangar afangi = Afangar.getAfangi(single.afangi_id);
            Verkefni verk1 = Verkefni.findProjectByVerkefniID(single.verkefni_id);

            if (verk1.tegund.equals("verkefni") && today.before(lokadagsetning)) {
                openProjects.add(new Project(verk1.heiti, grade, verk1.vaegi, afangi.namsgrein_afanganr, false, upphafs, lokaOpen, "project", verk1.verkefni_id,single.getHopur_id(),lokadagsetning));
            } else if (verk1.tegund.equals("verkefni") && today.after(lokadagsetning)) {
                closedProjects.add(new Project(verk1.heiti, grade, verk1.vaegi, afangi.namsgrein_afanganr, false, upphafs, lokaClosed, "project", verk1.verkefni_id,single.getHopur_id(),lokadagsetning));
            }
        }
        openProjects = CommonController.sortProjectsByDate(openProjects);
        closedProjects = CommonController.sortProjectsByDate(closedProjects);
        return ok(teacherAssignments.render(openProjects, closedProjects, oldAssignments));
    }

    //VIEW TEACHERONEASSIGNMENT
    //Information about one assignments, like startdate, enddate, how many student have submitted it and so on.
    //If the deadline has passed then the teacher can also submit grades for his students.
    public static Result teacherOneAssignment(int verkefni_id, int hopur_id) {
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        Verkefni verkefni = Verkefni.findProjectByVerkefniID(verkefni_id);
        verkefnihops vh = verkefnihops.findProjectByVerkefniIDHopsID(verkefni_id, hopur_id);
        Date upphafsdagsetning = vh.getUpphafsdagsetning();
        Date lokadagsetning = vh.getLokadagsetning();
        String upphafs = simpleDateFormat.format(upphafsdagsetning);
        String loka = simpleDateFormat.format(lokadagsetning);
        Date now = new Date();
        Boolean skilafresturLidinn;
        if (lokadagsetning.before(now)) {
            skilafresturLidinn = true;
        } else {
            skilafresturLidinn = false;
        }
        java.util.List<verkefninemenda> nemendur = verkefninemenda.findAllNemendurByVerkefniId(verkefni_id);
        int heildarfjoldi = nemendur.size();
        int skilafjoldi = 0;       //nr of students that ahve handed in the project
        for(verkefninemenda vnem : nemendur){
            if(verkefnaskil.findByVerkefniNemandiID(vnem.getNemandi_id(), vnem.getVerkefninemanda_id()) != null){
                skilafjoldi++;
            }
        }
        int ekkiskilad = heildarfjoldi-skilafjoldi; //nr of students that haven't handed in the project
        java.util.List<Students> students = Students.createStudentList(nemendur);
        for(verkefninemenda vnem : nemendur){
            for(Students student : students){
                if(vnem.getNemandi_id().equals(student.getNemandi_id())){
                    student.setVerkefninemenda_id(vnem.getVerkefninemanda_id());
                     if(vnem.getEinkunn() < 20.0){
                         student.setEinkunn(vnem.getEinkunn());
                     }
                    else{
                         student.setEinkunn(20.0);
                     }
                }
            }
        }
        CommonController.sortStudentsByName(students);
        boolean vidhengiNemenda = Vidhengitaflanemendur.vidhengiVerkefniHopsEmpty(vh.getVerkefnihops_id());
        int verkefnihopsID = vh.getVerkefnihops_id();
        return ok(teacherOneAssignment.render(verkefni, vh, upphafs, loka, skilafresturLidinn, students, nemendur, fillCommentList(verkefni_id),hopur_id,skilafjoldi,ekkiskilad,vidhengiNemenda, verkefnihopsID));
    }

    // <editor-fold desc="COMMENT FÖLL">
    //All comments for a particular project
    public static List<Comments> fillCommentList(int verkefni_id){
        List<Athugasemdir> athugasemdir = Athugasemdir.getAthugasemdirByVerkefniId(verkefni_id);
        List<Comments> commentList = new ArrayList<Comments>();
        if (athugasemdir != null){
            commentList = Comments.createCommentList(athugasemdir); }
        return commentList;
    }

    //When a teacher submits an announcement for a particular course he's teaching.
    public static Result uploadAnnouncements(int sida) {
        String teacherId = session().get("notandiId");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        String[] fyrirsogn = request().body().asFormUrlEncoded().get("fyrirsogn");
        String[] texti = request().body().asFormUrlEncoded().get("texti");
        String[] afangi_id = request().body().asFormUrlEncoded().get("afangi_id");
        //Ef enginn áfangi er valinn birtist þetta fyrir alla
        if(!(fyrirsogn[0].equals("") && texti[0].equals(""))){
            Tilkynning tilkynning = Tilkynning.create(teacherId, afangi_id[0], fyrirsogn[0], texti[0]);
        }

        if(sida == 1){
            return redirect(routes.TeacherController.allTeacherAnnouncements());
        }else if(sida == 2){
            return redirect(routes.TeacherController.teacherCourses(0,0));
        }else{
            return redirect(routes.TeacherController.teacherDashboard());
        }

    }

    //Allows teacher to deleta an announcement he made.
    public static Result deleteAnnouncement(int announcementId) {
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        Tilkynning.deleteTilkynning(announcementId);
        return redirect(routes.TeacherController.allTeacherAnnouncements());
    }

    //Shows the teacher the student's solution to the project and if the question is a singlechoice or multichoice we bold the correct answer.
    public static Result getOneAssignment(int verkNemId, int verkefni_id, String heiti, String nafnNemenda){
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        List<Verkefnaspurningar> verkspurn = Verkefnaspurningar.getByVerkefniID(verkefni_id); //get all the questions for this particular assignment
        List<Spurningar> spurn = Spurningar.findByVerkSpurn(verkspurn);
        List<QuestionAndAnswers> qa = new ArrayList<QuestionAndAnswers>();
        verkefnaskil verkefnaskilNemanda ;
        int verkefnaskil_id = 0;
        String athugasemdNemanda = null;
        if(verkefnaskil.findByVerkefniNemandaID(verkNemId) == null){
            verkefnaskilNemanda = null;
        }
        else{
            verkefnaskilNemanda = verkefnaskil.findByVerkefniNemandaID(verkNemId);
            athugasemdNemanda = verkefnaskilNemanda.athugasemd;
            verkefnaskil_id = verkefnaskilNemanda.verkefnaskil_id;
        }
        for(Spurningar sp : spurn){ //go through all the questions and depending on the type of the question we want to display different things.
            if(sp.getTegund().equals("mynd")){
                byte[] vidhengi = Vidhengitafla.getVidhengi(sp.getSpurningar_id());
                String encodedImage = Base64.encode(vidhengi); //need to encode the image to be able to display it.
                if(verkefnaskilNemanda != null){
                    List<Verkefnaskilspurningar> verkefnaskilspurningar = Verkefnaskilspurningar.getSvorWithVerkefniID(verkefnaskil_id, sp.getSpurningar_id());
                    qa.add(new QuestionAndAnswers(sp.getSpurningar_id(), sp.getTexti(), sp.getTegund(), encodedImage,returnWeight(verkspurn,sp.getSpurningar_id()),verkefnaskilspurningar.get(0).getSvar()));
                }
                else{
                    qa.add(new QuestionAndAnswers(sp.getSpurningar_id(), sp.getTexti(), sp.getTegund(), encodedImage,returnWeight(verkspurn,sp.getSpurningar_id())));
                }
            }
            if(sp.getTegund().equals("krossar")){
                List<Svor> svor = Svor.getSvorBySpurningID(sp.getSpurningar_id());
                List<Integer> svorID = new ArrayList<Integer>();
                Integer rettSvar = 0; //Saves the coorect answer so we can bold it
                Integer svarNemanda = 0;
                List<String>svorSpurningar  = new ArrayList<String>();
                for(Svor s: svor){
                    svorSpurningar.add(s.getTexti());
                    svorID.add(s.getSvar_id());
                    if(s.getRettsvar() == 1){
                        rettSvar = s.getSvar_id();
                    }
                }
                if(verkefnaskilNemanda != null){  //if the student has submitted the project we want to display is answers.
                    List<Verkefnaskilspurningar> vskil = Verkefnaskilspurningar.getSvorWithVerkefniID(verkefnaskil_id,sp.getSpurningar_id());
                    svarNemanda = Integer.parseInt(vskil.get(0).getSvar());
                    qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),sp.getTegund(),svorSpurningar,returnWeight(verkspurn,sp.getSpurningar_id()),svorID,rettSvar, svarNemanda));
                }
                else{
                    qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),sp.getTegund(),svorSpurningar,returnWeight(verkspurn,sp.getSpurningar_id()),svorID,rettSvar));
                }
            }
            if(sp.getTegund().equals("fjolval")){
                List<Svor> svor = Svor.getSvorBySpurningID(sp.getSpurningar_id());
                List<String>svorSpurningar  = new ArrayList<String>();
                List<Integer> svorID = new ArrayList<Integer>();
                List<Integer> rettSvor = new ArrayList<Integer>();//A list of the correct answers we want to bold
                for(Svor s: svor){
                    svorSpurningar.add(s.getTexti());
                    svorID.add(s.getSvar_id());
                    if(s.getRettsvar() == 1){
                        rettSvor.add(s.getSvar_id());
                    }
                }
                List<Integer> rettSvorList = new ArrayList<Integer>();
                for(Integer svarID : svorID){
                    if(isCorrectAnswerFjolval(rettSvor,svarID)== true){
                        rettSvorList.add(1);
                    }
                    else{
                        rettSvorList.add(0);
                    }

               }
                if(verkefnaskilNemanda != null){
                    List<Integer> nemendaSvorList = new ArrayList<Integer>();//List of the students answer.
                    List<Verkefnaskilspurningar> vskil = Verkefnaskilspurningar.getSvorWithVerkefniID(verkefnaskil_id,sp.getSpurningar_id());
                    for(Integer svarID: svorID){
                        if(isStudentAnswerFjolval(vskil,svarID) == true){
                            nemendaSvorList.add(1);
                        }
                        else{
                            nemendaSvorList.add(0);
                        }
                    }
                    qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),sp.getTegund(),svorSpurningar,returnWeight(verkspurn,sp.getSpurningar_id()),svorID,rettSvorList, nemendaSvorList));

                }
                else{
                    qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),sp.getTegund(),svorSpurningar,returnWeight(verkspurn,sp.getSpurningar_id()),svorID,rettSvorList));
                }
            }
            if(sp.getTegund().equals("texti")){
                if(verkefnaskilNemanda != null){
                    List<Verkefnaskilspurningar> verkefnaskilspurningar = Verkefnaskilspurningar.getSvorWithVerkefniID(verkefnaskil_id,sp.getSpurningar_id());
                    qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),sp.getTegund(),returnWeight(verkspurn,sp.getSpurningar_id()),verkefnaskilspurningar.get(0).getSvar()));
                }
                else{
                    qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),sp.getTegund(),returnWeight(verkspurn,sp.getSpurningar_id())));
                }
            }
            if(sp.getTegund().equals("eydufylling")){
                List<Svor> eydufyll = Svor.getSvorBySpurningID(sp.getSpurningar_id());
                List<String> strings = HelperFunctions.splitEydufylling(eydufyll.get(0).getTexti()); //We split the string to create the gaps to fill in
                if(verkefnaskilNemanda != null){
                    List<Verkefnaskilspurningar> verkefnaskilspurningar = Verkefnaskilspurningar.getSvorWithVerkefniID(verkefnaskil_id,sp.getSpurningar_id());
                    List<String> svor = new ArrayList<String>();
                    for(Verkefnaskilspurningar verkefnasvor : verkefnaskilspurningar){
                        svor.add(verkefnasvor.getSvar());
                    }
                    qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),strings,sp.getTegund(),returnWeight(verkspurn,sp.getSpurningar_id()),svor));

                }
                else{
                    qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),strings,sp.getTegund(),returnWeight(verkspurn,sp.getSpurningar_id())));
                }
            }

        }
        if(spurn.isEmpty()){
            qa= null;
        }
        //Get a list of all the attachment the student submitted.
        List<Vidhengitaflanemendur> vidhengiNemenda = null;
        if(Vidhengitaflanemendur.getVidhengiList(verkefnaskil_id) != null){
            vidhengiNemenda = Vidhengitaflanemendur.getVidhengiAll(verkefnaskil_id);
        }

         return ok(assignmentFromStudent.render(qa, heiti, nafnNemenda, athugasemdNemanda, vidhengiNemenda));
    }

    //Shows the teacher information about a particular project
    public static Result assignment(int verkefniId, String heiti){
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        List<Verkefnaspurningar> verkspurn = Verkefnaspurningar.getByVerkefniID(verkefniId); //Find the questions that are for this project
        List<Spurningar> spurn = Spurningar.findByVerkSpurn(verkspurn);//get all the questions
        List<QuestionAndAnswers> qa = new ArrayList<QuestionAndAnswers>();
        List<Vidhengitafla> vidhengiTilAdSkila = new ArrayList<Vidhengitafla>();

        for(Spurningar sp : spurn){    //Go through all the questions because we want to display different things depending on the questions.
            if(sp.getTegund().equals("mynd")){
                byte[] vidhengi = Vidhengitafla.getVidhengi(sp.getSpurningar_id());
                String encodedImage = Base64.encode(vidhengi);     //Have to encode the image to be able to display it
                qa.add(new QuestionAndAnswers(sp.getSpurningar_id(), sp.getTexti(), sp.getTegund(), encodedImage,returnWeight(verkspurn,sp.getSpurningar_id())));
            }
            if(sp.getTegund().equals("krossar")){
                List<Svor> svor = Svor.getSvorBySpurningID(sp.getSpurningar_id());
                List<Integer> svorID = new ArrayList<Integer>();
                Integer rettSvar = 0; //So we can bold the correct answer
                List<String>svorSpurningar  = new ArrayList<String>();
                for(Svor s: svor){
                    svorSpurningar.add(s.getTexti());
                    svorID.add(s.getSvar_id());
                    if(s.getRettsvar() == 1){
                        rettSvar = s.getSvar_id();
                    }
                }
                qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),sp.getTegund(),svorSpurningar,returnWeight(verkspurn,sp.getSpurningar_id()),svorID,rettSvar));
            }
            if(sp.getTegund().equals("fjolval")){
                List<Svor> svor = Svor.getSvorBySpurningID(sp.getSpurningar_id());
                List<String>svorSpurningar  = new ArrayList<String>();
                List<Integer> svorID = new ArrayList<Integer>();
                List<Integer> rettSvor = new ArrayList<Integer>(); //All the correct answers to bold them.
                for(Svor s: svor){
                    svorSpurningar.add(s.getTexti());
                    svorID.add(s.getSvar_id());
                    if(s.getRettsvar() == 1){
                        rettSvor.add(s.getSvar_id());
                    }
                }
                List<Integer> rettSvorList = new ArrayList<Integer>();
                for(Integer svarID : svorID){
                    if(isCorrectAnswerFjolval(rettSvor,svarID)== true){
                        rettSvorList.add(1);
                    }
                    else{
                        rettSvorList.add(0);
                    }

                }
                qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),sp.getTegund(),svorSpurningar,returnWeight(verkspurn,sp.getSpurningar_id()),svorID,rettSvorList));
            }
            if(sp.getTegund().equals("texti")){
                qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),sp.getTegund(),returnWeight(verkspurn,sp.getSpurningar_id())));
            }
            if(sp.getTegund().equals("vidhengi")){
                vidhengiTilAdSkila.add(Vidhengitafla.getVidhengiAll(sp.getSpurningar_id()));
            }
            if(sp.getTegund().equals("eydufylling")){
                List<Svor> eydufyll = Svor.getSvorBySpurningID(sp.getSpurningar_id());
                List<String> strings = HelperFunctions.splitEydufylling(eydufyll.get(0).getTexti());//Need to split the string to be able to put the inputfields where they are suppose to be
                qa.add(new QuestionAndAnswers(sp.getSpurningar_id(),sp.getTexti(),strings,sp.getTegund(),returnWeight(verkspurn,sp.getSpurningar_id())));
            }

        }
        if(spurn.isEmpty()){
            qa= null;
        }
        return ok(assignment.render(qa, vidhengiTilAdSkila, heiti));
    }

    //Returns the weight of a question, use this so we don't have a triple forlooop
    public static Double returnWeight(List<Verkefnaspurningar>verkefnaspurningar, int spurn_id){
        for(Verkefnaspurningar vskil : verkefnaspurningar){
            if(vskil.getSpurningar_id() == spurn_id){
                return vskil.getVaegi();
            }
        }
        return 0.0;
    }

    //Allows the teacher to submit grades for his students for a particular project
    public static Result submitGrades(){
        String[] postAction = request().body().asFormUrlEncoded().get("nemandi_id");
        String[] gradeAction = request().body().asFormUrlEncoded().get("grade");
        int numberOfStudents = postAction.length;
        String[] verkefni = request().body().asFormUrlEncoded().get("verkefni_id");
        String[] hopur_id = request().body().asFormUrlEncoded().get("hopur_id");
        String Stringverkefni_id = verkefni[0];
        Integer verkefni_id = Integer.parseInt(Stringverkefni_id);
        String athugasemd_kennara = "";
        String umsogn_kennara = "";
        if(postAction != null){
            for(int index = 0; index < numberOfStudents ; index++){
                String student_id = postAction[index];
                String grade = gradeAction[index];
                if(!(grade.equals(""))){
                    verkefninemenda.submitGrade(verkefni_id, student_id, grade, athugasemd_kennara, umsogn_kennara);
                }
            }
        }
        return redirect(routes.TeacherController.teacherOneAssignment(verkefni_id, Integer.parseInt(hopur_id[0])));
    }

    //Checks if an answer is the correct answer to that multichoice question.
    public static boolean isCorrectAnswerFjolval(List<Integer> rettSvor, Integer svar_id){
        for(Integer a : rettSvor){
            if(a.equals(svar_id)){
                return true;
            }
        }
        return false;
    }
    //Checks if students answer is the correct answer to the multichoice question.
    public static boolean isStudentAnswerFjolval(List<Verkefnaskilspurningar> studentSvar, Integer svar_id ){
        for(Verkefnaskilspurningar verk : studentSvar){
            if(Integer.parseInt(verk.getSvar()) == svar_id){
                return true;
            }
        }
        return false;
    }
    // <editor-fold desc=ASSIGNMENT-GROUPS">

    //Allows the teacher to assign a project to a group
    public static Result assignmentToGroups(int verkefniId){
        String teacherID = session().get("notandiId");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        Verkefni verkefni = Verkefni.find.byId(verkefniId);
        List<List<vNemandiAfangarOnn>> listNem = new ArrayList<List<vNemandiAfangarOnn>>();
        List<vKennariHoparOnn> afangar = new ArrayList<vKennariHoparOnn>();
        for(vKennariHoparOnn vk : classes){
            if(vk.getAfangi_id() == Integer.parseInt(verkefni.getAfangi_id())){
                afangar.add(vk);
                List<vNemandiAfangarOnn> nemandiAfangarOnn = vNemandiAfangarOnn.getNemendurHop(vk.hopur_id);
                listNem.add(nemandiAfangarOnn);
            }
        }
        String afangaNafn = "";
        if(afangar != null){
            afangaNafn = afangar.get(0).namsgrein_afanganr;
        }
        return ok(assignmentToGroup.render(verkefniHopsForm, afangar, verkefni, teacherID, listNem, afangaNafn));
    }
    //Teacher chooses to assign the project for a particular group so we have to assign the project to that group and all the students in that group.
    public static Result submitAssignmentToGroup(int verkefni_id){
        Form<verkefnihops> verkHops = form(verkefnihops.class).bindFromRequest();

        if(verkHops.hasErrors()){
            flash("success", "Villa kom upp");
            return redirect(routes.TeacherController.assignmentToGroups(verkefni_id));
        }
        verkefnihops verkefnihop = verkefnihops.findProjectByVerkefniIDHopurID(verkefni_id, verkHops.get().hopur_id);
        if(verkefnihop == null){
            verkefnihop = verkefnihops.create(verkHops.get().upphafsdagsetning, verkHops.get().lokadagsetning, verkHops.get().verkefni_id,
                    verkHops.get().hopur_id, verkHops.get().afangi_id, verkHops.get().athugasemd, verkHops.get().kennari_id, verkHops.get().hopskil);
        }

        String[] postAction = request().body().asFormUrlEncoded().get("nemendur");
        int valdirNem = postAction.length;
        if(postAction != null){
            for(int index = 0; index < valdirNem ; index++){
                String notandiId = postAction[index];
                if(!(notandiId.equals(""))){
                    verkefninemenda verkNem = verkefninemenda.findByUserAndVerkefniID(verkHops.get().verkefni_id, notandiId);
                    if(verkNem == null){
                        verkNem = verkefninemenda.create(verkefnihop.verkefnihops_id, notandiId, verkHops.get().athugasemd, verkHops.get().verkefni_id);
                    }
                }
            }
            }

        return redirect(routes.TeacherController.teacherOneAssignment(verkefni_id, verkefnihop.getHopur_id()));
    }

    //Allows the teacher to change the deadline
    public static Result changeDeadline(int verkefniHopsId){
        String[] postAction = request().body().asFormUrlEncoded().get("lokadagsetning");
        String nyDags = postAction[0];
        verkefnihops verkhops = verkefnihops.findProjectByVerkefniHopsID(verkefniHopsId);
        try {
            Date date = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse(nyDags);
            verkhops.setLokadagsetning(date);
            verkhops.update();
        } catch (ParseException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return redirect(routes.TeacherController.teacherOneAssignment(verkhops.getVerkefni_id(), verkhops.getHopur_id()) );
    }

    //information about all the courses the teacher is teaching this semester
    public static Result teacherCourses(int afangi_id, int hopur_id){
        String teacherId =session().get("notandiId");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        int intNotandi = Integer.parseInt(teacherId);
        List<Announcements> tilkynningar = new ArrayList<Announcements>();
        List<Announcements> top5Tilkynningar = new ArrayList<Announcements>();
        List<Students> students = new ArrayList<Students>();
        List<Project> projects = new ArrayList<Project>();
        List<verkefnihops> verkefniHops = verkefnihops.findProjectByTeacher(teacherId);
        List<Verkefni> verkefni = new ArrayList<Verkefni>();
        List<Baekur> baekur = new ArrayList<Baekur>();
        List<vAfangarBaekur> allarBaekur = vAfangarBaekur.findAll();
        for(verkefnihops vh : verkefniHops){  //to get the begin and handin date
            verkefni.add(Verkefni.findProjectByVerkefniID(vh.getVerkefni_id()));
        }
        //For each course we want to find announcements, projects, students and books etc.
        for(vKennariHoparOnn afangi : classes){
            //Tilkynningar

            List<Tilkynning> tilkynning = Tilkynning.getAfangiTilkynningarSorted(Integer.toString(afangi.getAfangi_id()));
            List<Announcements> tempTilkynning = new ArrayList<Announcements>();
            for(Tilkynning t: tilkynning){    //Get all the announcment for the courses the teacher teaches
                 if(Integer.parseInt(t.getAfangi_id()) == afangi.getAfangi_id() && (t.getHopur_id() == afangi.getHopur_id() || t.getHopur_id() == 0)){
                     tempTilkynning.add(new Announcements(t.getTexti(),simpleDateFormat.format(t.getDagur_stofnad()),t.getFyrirsogn(),t.getAfangi_id()));
                 }
            }
            List<Announcements> temp5Tilkynning = new ArrayList<Announcements>();
            if(tempTilkynning != null && tempTilkynning.size()>=5){  //We want to display the 5 newest so if the announcements are more than five we display the five newest
                for(int i = 0; i < 5 ; i++){
                    temp5Tilkynning.add(new Announcements(tempTilkynning.get(i).getTexti(), tempTilkynning.get(i).getDagur_stofnad(), tempTilkynning.get(i).getFyrirsogn(), tempTilkynning.get(i).getAfangi_id()));
                }
            }
            if(tempTilkynning != null && tempTilkynning.size() < 5){//If the announcements are fewer than 5 we just display all the announcements.
                for(int i = 0; i < tempTilkynning.size() ; i++){
                    temp5Tilkynning.add(new Announcements(tempTilkynning.get(i).getTexti(), tempTilkynning.get(i).getDagur_stofnad(), tempTilkynning.get(i).getFyrirsogn(), tempTilkynning.get(i).getAfangi_id()));
                }
            }

            if(tempTilkynning == null){
                temp5Tilkynning = null;
            }
            tilkynningar.add(new Announcements(afangi.getAfangi_id(),afangi.getHopur_id(),tempTilkynning));
            top5Tilkynningar.add(new Announcements(afangi.getAfangi_id(),afangi.getHopur_id(), temp5Tilkynning));
            //Nemendalistar
            List<vNemandiAfangarOnn> temp = vNemandiAfangarOnn.findStudentsByGroup(afangi.getHopur_id());
            List<Students> tempStudents = new ArrayList<Students>();
            //All the students in the courses the teacher is teaching
            for(vNemandiAfangarOnn v: temp){
                tempStudents.add(new Students(Integer.toString(v.getNotandi_id()),v.getNafn(),v.getHopur(),v.getKennitala()));

            }
            students.add(new Students(afangi.getAfangi_id(), afangi.getHopur_id(), tempStudents));
            //Verkefni og próf
            List<Project> tempProject = new ArrayList<Project>();
            for(verkefnihops vhops: verkefniHops){
                for(Verkefni v: verkefni){
                    if(vhops != null && v != null){
                        if(afangi.getAfangi_id() == Integer.parseInt(v.getAfangi_id())&& vhops.getVerkefni_id() == v.getVerkefni_id() && afangi.getHopur_id() == vhops.getHopur_id()){
                            tempProject.add(new Project(v.getHeiti(),afangi.getAfangi_id(),vhops.getUpphafsdagsetning(),vhops.getLokadagsetning(),v.getVaegi(),v.getVerkefni_id(),v.getTegund(),afangi.getHopur_id()));
                        }
                    }

                }
            }

            tempProject = CommonController.sortProjectsByDate(tempProject);
            Date today = new Date();
            List<Project> openProject = new ArrayList<Project>();
            List<Project> closedProject = new ArrayList<Project>();
            for(Project proj : tempProject){
                if(afangi.getAfangi_id() == proj.getAfangi_id()){
                    String beginDate = simpleDateFormat.format(proj.getBeginDateFormat());
                    String endDate = simpleDateFormat.format(proj.getHandinDateFormat());
                    if(today.before(proj.getHandinDateFormat())){
                        closedProject.add(new Project(proj.getName(),proj.getAfangi_id(),beginDate,endDate, proj.getWeight(),proj.getVerkefni_id(),proj.getType()));
                    }
                    else{
                        openProject.add(new Project(proj.getName(),proj.getAfangi_id(),beginDate,endDate, proj.getWeight(),proj.getVerkefni_id(),proj.getType()));
                    }
                }
            }
            if(openProject != null && closedProject != null){
                projects.add(new Project(afangi.getAfangi_id(),afangi.getHopur_id(),openProject,closedProject));
            }
            if(openProject == null && closedProject != null){
                projects.add(new Project(afangi.getAfangi_id(),afangi.getHopur_id(),null,closedProject));
            }
            if(openProject != null && closedProject == null){
                projects.add(new Project(afangi.getAfangi_id(),afangi.getHopur_id(),openProject,null));
            }
            else{
                projects.add(new Project(afangi.getAfangi_id(),afangi.getHopur_id(),null,null));

            }
            List<Baekur> bokHofundur = new ArrayList<Baekur>();
            for(vAfangarBaekur afangaBaekur : allarBaekur){
                if(afangaBaekur.getAfangi_id() == afangi.getAfangi_id()){
                    if(bookAlreadyForCourse(baekur,afangaBaekur.getAfangi_id())== false){
                        if(afangaBaekur.getHeiti() == null){
                            bokHofundur.add(new Baekur(null,afangaBaekur.getHofundur()));
                        }
                        if(afangaBaekur.getHofundur() == null){
                            bokHofundur.add(new Baekur(afangaBaekur.getHeiti(),null));
                        }
                        if(afangaBaekur.getHeiti() != null && afangaBaekur.getHofundur() != null){
                            bokHofundur.add(new Baekur(afangaBaekur.getHeiti(),afangaBaekur.getHofundur(), afangaBaekur.getUtgafa(),afangaBaekur.getUtgefandi()));
                        }
                    }
                }
            }
            if(bokHofundur.size() == 0){
                bokHofundur = null;
            }
            if(bokHofundur != null){
                bokHofundur = CommonController.sortBooksByName(bokHofundur);
                baekur.add(new Baekur(afangi.getAfangi_id(),bokHofundur));
            }
            else{
                baekur.add(new Baekur(afangi.getAfangi_id(),null));
            }


        }

        return ok(teacherCourses.render(classes, tilkynningar, top5Tilkynningar, afangi_id, students, projects, hopur_id, baekur)) ;

    }

    public static boolean bookAlreadyForCourse(List<Baekur> baekur, int afangi_id){
        if(baekur == null){
            return false;
        }
        else{
            for(Baekur bok : baekur){
                if(bok.getAfangi_id() == afangi_id){
                    return true;
                }
            }
        }
        return false;
    }
    //To display all announcements for the courses the teacher is teaching and for the whole school
    public static Result allTeacherAnnouncements() {
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        List<Tilkynning> tilkynningList = Tilkynning.getAllTeacherAnnouncements(classes);
        List<Announcements> announcements = Announcements.createAnnouncementList(tilkynningList);
        return ok(AllTeacherAnnouncements.render(announcements, classes));
    }
    //Allows the teachert to assign homework for a particular class in the timetable
    public static Result uploadHomework() {
        Date now = new Date(); //date when homework
        String teacherId = session().get("notandiId");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }
        String[] texti = request().body().asFormUrlEncoded().get("texti");
        String[] timeslot = request().body().asFormUrlEncoded().get("timeslot"); //the timslot the teacher is putting his homework on
        Integer intTimeslot = Integer.parseInt(timeslot[0]);


        //try to find the date for the homework
        Calendar newC = new GregorianCalendar();
        newC.setTime(now);
        newC.setFirstDayOfWeek(Calendar.MONDAY);
        int today = newC.get(Calendar.DAY_OF_WEEK);
        if (intTimeslot>0&&intTimeslot <9){
            newC.add(Calendar.DAY_OF_WEEK,-today+Calendar.MONDAY); //the day the homework is supposed to be on is monday of the current week
        }
        if (intTimeslot>8&&intTimeslot <17){
            newC.add(Calendar.DAY_OF_WEEK,-today+Calendar.TUESDAY); //the day the homework is supposed to be on is tuesday of the current week
        }
        if (intTimeslot>16&&intTimeslot <25){
            newC.add(Calendar.DAY_OF_WEEK,-today+Calendar.WEDNESDAY); //the day the homework is supposed to be on is wednesday of the current week
        }
        if (intTimeslot>24&&intTimeslot <33){
            newC.add(Calendar.DAY_OF_WEEK,-today+Calendar.THURSDAY); //the day the homework is supposed to be on is thursdayof the current week
        }
        if (intTimeslot>32&&intTimeslot <41){
            newC.add(Calendar.DAY_OF_WEEK,-today+Calendar.FRIDAY); //the day the homework is supposed to be on is friday of the current week
        }

        TimetableHomework course = new TimetableHomework();
        List<List<Stundatoflur_NK>> stundatafla = Stundatoflur_NK.getStundataflaKennara(classes);  //List that has a seperate list for the course schedule each day
        List<List<Heimavinna>> heimavinna = Heimavinna.getTeacherHomeworkWeek(classes);  //List that has a seperate list for the homework each day
        List<TimetableHomework> All = TimetableHomework.makeTimetableHomework(stundatafla, heimavinna);
        for(TimetableHomework single:All){   //All is the courseTable for the teacher. I have to use this to know what course it is that has the timeslot id
            if(intTimeslot==single.getId()){ //if timeslot we get from the view is the same as the id of the a href we clicked in the view, we have the right course
                course=single;
            }

        }
        Heimavinna heima = Heimavinna.createHomework(intTimeslot,course.getHopur_id(), course.getAfangi_id(),newC.getTime(),texti[0]);

        return redirect(routes.TeacherController.teacherDashboard());
    }

    //Get all discussions for the projects the teacher created
    public static Result allTeacherDiscussions(){
        List<Athugasemdir> athugasemdir = Athugasemdir.getAllTeacherDiscussions(teacherId);
        List<Comments> allComments = Comments.createCommentList(athugasemdir);
        return ok(AllTeacherDiscussions.render(allComments));
    }

    public static Result teacherTimeTable(){
        List<List<Stundatoflur_NK>> stundatafla = Stundatoflur_NK.getStundataflaKennara(classes);  //List that has a seperate list for the course schedule each day
        List<List<Heimavinna>> heimavinna = Heimavinna.getTeacherHomeworkWeek(classes);  //List that has a seperate list for the homework each day
        List<TimetableHomework> All = TimetableHomework.makeTimetableHomework(stundatafla, heimavinna);

        List<TimetableHomework> oneRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> twoRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> threeRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> fourRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> fiveRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> sixRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> sevenRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> eightRow=new ArrayList<TimetableHomework>();
        for(int i=0;i<40;i= i+8){
            if(All.get(i).getId()==(i+1)){
                oneRow.add(All.get(i));
            }
        }
        for(int i=1;i<40;i= i+8){
            if(All.get(i).getId()==(i+1)){
                twoRow.add(All.get(i));
            }
        }
        for(int i=2;i<40;i= i+8){
            if(All.get(i).getId()==(i+1)){
                threeRow.add(All.get(i));
            }
        }
        for(int i=3;i<40;i= i+8){
            if(All.get(i).getId()==(i+1)){
                fourRow.add(All.get(i));
            }
        }
        for(int i=4;i<40;i= i+8){
            if(All.get(i).getId()==(i+1)){
                fiveRow.add(All.get(i));
            }
        }
        for(int i=5;i<40;i= i+8){
            if(All.get(i).getId()==(i+1)){
                sixRow.add(All.get(i));
            }
        }
        for(int i=6;i<40;i= i+8){
            if(All.get(i).getId()==(i+1)){
                sevenRow.add(All.get(i));
            }
        }
        for(int i=7;i<40;i= i+8){
            if(All.get(i).getId()==(i+1)){
                eightRow.add(All.get(i));
            }
        }

        return ok(TeacherTimeTable.render(oneRow, twoRow, threeRow, fourRow, fiveRow, sixRow, sevenRow, eightRow));


    }

    //Get the name of a course for a particular id
    public static String getAfangiNamsgrein(int afangi_id){
        for(vKennariHoparOnn single:classes){
            if(single.afangi_id==afangi_id){
                return single.namsgrein_afanganr;
            }
        }
        return "";
    }

    //returns a list of all questions that have been created
    public static Result questionBank() {
        String notandiID = session().get("notandiId");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }

        List<Spurningar> spurningar = Spurningar.findAllSpurningarByAfangiList(classes);
        List<Spurningar_leitarskilyrdi> sp_leit = Spurningar_leitarskilyrdi.getAllSpurningar_leitarskilyrdi();


        List<Question> questions = new ArrayList<Question>();

        for(Spurningar spurning : spurningar){
            String dagurbuidtil = simpleDateFormat.format(spurning.dagurstofnad);

            List<Leitarskilyrdi> tags = new ArrayList<Leitarskilyrdi>();
            for(Spurningar_leitarskilyrdi spurn : sp_leit){
                if(spurning.spurningar_id.equals(spurn.spurning_id)){
                    tags.add(Leitarskilyrdi.findById(spurn.leitarskilyrdi_id));
                }
            }
            String namsgr_afanganr = getAfangiNamsgrein(Integer.parseInt(spurning.afangi_id));

            questions.add(new Question(spurning.spurningar_id,spurning.tegund,spurning.onn_id,spurning.texti,spurning.afangi_id,spurning.tyngdarstig,
                    spurning.kennari_id,spurning.kafli,spurning.vidhengi,spurning.nr_utgafu,spurning.hofundur_bokar,dagurbuidtil, tags,spurning.bok_nafn,namsgr_afanganr));

        }
        return ok(QuestionBank.render(questions,classes , Annir.fillSemesterList(notandiID)));

    }

    //Allows the teacher to change a text question
    public static Result changeTextQuestion(int questionId){
        String notandiID = session().get("notandiId");
        Spurningar spurning = new Spurningar("","",24100,"",1);
        Date now = new Date();

        spurning=Spurningar.getByID(questionId);//get the question
        List<vAfangarBaekur> baekur = new ArrayList<vAfangarBaekur>();
        vAfangarBaekur bok = new vAfangarBaekur();
        String bokHeiti = new String();
        if (!(spurning.bok_id.equals("noBook"))){
            baekur = vAfangarBaekur.getBokFromId(Integer.parseInt(spurning.bok_id));
            bok = baekur.get(0);
            bokHeiti=bok.getHeiti();
            System.out.println(bokHeiti);
        }
        else{
            bokHeiti = "Spurning ekki úr bók";
        }
        List<vKennariHoparOnn> vk = vKennariHoparOnn.getCourseList(Integer.parseInt(notandiID), Integer.parseInt(spurning.afangi_id)); //get the course this question is for
        String edit=simpleDateFormat.format(spurning.getDagurstofnad());

        Question question = new Question(spurning.spurningar_id, "texti", spurning.texti, spurning.afangi_id, spurning.tyngdarstig,notandiID, now, bokHeiti, vk.get(0).getNamsgrein_afanganr());

        return ok(changeTextQuestion.render(question));//(questionForm,spurning));
    }
    //Changes the text question that the teacher choose to change
    public static Result changedTextQuestion(){

        String[] spurningar_id = request().body().asFormUrlEncoded().get("spurningar_id");
        String[] changed_text = request().body().asFormUrlEncoded().get("texti");
        Spurningar.changeQuestion(Integer.parseInt(spurningar_id[0]), changed_text[0]);
        return redirect(routes.TeacherController.questionBank());
    }
    //Allows the teacher to change a sentence completion question
    public static Result changeEydufyllingQuestion(int questionId){
        String notandiID = session().get("notandiId");
        Spurningar spurning = new Spurningar("","",24100,"",1);
        Date now = new Date();

        spurning=Spurningar.getByID(questionId);
        List<Svor> eydufyllingSvor = Svor.getSvorBySpurningID(questionId);
        Svor svar = eydufyllingSvor.get(0);
        List<vAfangarBaekur> baekur = new ArrayList<vAfangarBaekur>();
        vAfangarBaekur bok = new vAfangarBaekur();
        String bokHeiti = "Spurning ekki úr bók";
        if (!spurning.bok_id.equals("noBook")){
            baekur = vAfangarBaekur.getBokFromId(Integer.parseInt(spurning.bok_id));
            bok = baekur.get(0);
            bokHeiti=bok.getHeiti();
        }

        List<vKennariHoparOnn> vk = vKennariHoparOnn.getCourseList(Integer.parseInt(notandiID), Integer.parseInt(spurning.afangi_id));
        String edit=simpleDateFormat.format(spurning.getDagurstofnad());

        Question question = new Question(spurning.spurningar_id, "eydufylling", spurning.texti, spurning.afangi_id, spurning.tyngdarstig,notandiID, now, bokHeiti, vk.get(0).getNamsgrein_afanganr());

        return ok(changeEydufyllingQuestion.render(question, svar));//(questionForm,spurning));
    }

    public static Result changedEydufyllingQuestion(){

        String[] spurningar_id = request().body().asFormUrlEncoded().get("spurningar_id");
        String[] changed_text = request().body().asFormUrlEncoded().get("eydulysing"); //spurningin í spurningatöflunni
        String[] changed_answer = request().body().asFormUrlEncoded().get("texti"); //svarið, eyðufyllingin sjálf í svor toflunni
        if(changed_text!= null){
            Spurningar.changeQuestion(Integer.parseInt(spurningar_id[0]), changed_text[0]);
        }
        if(changed_answer!=null){
            Svor.changeSvar(Integer.parseInt(spurningar_id[0]),changed_answer[0]);

        }
        return redirect(routes.TeacherController.questionBank());
    }

    public static Result changeSingleChoiceQuestion(int questionId){
        String notandiID = session().get("notandiId");
        Spurningar spurning = new Spurningar("","",24100,"",1);
        Date now = new Date();

        spurning=Spurningar.getByID(questionId);
        List<Svor> svor = Svor.getSvorBySpurningID(questionId);
        List<vAfangarBaekur> baekur = new ArrayList<vAfangarBaekur>();
        vAfangarBaekur bok = new vAfangarBaekur();
        String bokHeiti = "Spurning ekki úr bók";
        if (!spurning.bok_id.equals("noBook")){
            baekur = vAfangarBaekur.getBokFromId(Integer.parseInt(spurning.bok_id));
            bok = baekur.get(0);
            bokHeiti=bok.getHeiti();
        }
        List<vKennariHoparOnn> vk = vKennariHoparOnn.getCourseList(Integer.parseInt(notandiID), Integer.parseInt(spurning.afangi_id));
        String edit=simpleDateFormat.format(spurning.getDagurstofnad());

        Question question = new Question(spurning.spurningar_id, "krossar", spurning.texti, spurning.afangi_id, spurning.tyngdarstig,notandiID, now, bokHeiti, vk.get(0).getNamsgrein_afanganr());

        return ok(changeSingleChoiceQuestion.render(question, svor));//(questionForm,spurning));
    }

    public static Result changedSingleChoiceQuestion(){

        String[] spurningar_id = request().body().asFormUrlEncoded().get("spurningar_id");
        String[] changed_Question = request().body().asFormUrlEncoded().get("texti");
        String[] changed_right_answer = request().body().asFormUrlEncoded().get("svor_texti_rett");
        String[] changed_wrong_answer = request().body().asFormUrlEncoded().get("svor_texti");
        if(changed_Question!= null){
            Spurningar.changeQuestion(Integer.parseInt(spurningar_id[0]), changed_Question[0]);
        }
        if(changed_right_answer!=null||changed_wrong_answer!= null){
            Svor.changeSingleChoiceAnswers(Integer.parseInt(spurningar_id[0]), changed_right_answer[0], changed_wrong_answer);

        }
        return redirect(routes.TeacherController.questionBank());
    }

    public static Result changeMultiChoiceQuestion(int questionId){
        String notandiID = session().get("notandiId");
        Spurningar spurning = new Spurningar("","",24100,"",1);
        Date now = new Date();

        spurning=Spurningar.getByID(questionId);
        List<Svor> svor = Svor.getSvorBySpurningID(questionId);
        List<vAfangarBaekur> baekur = new ArrayList<vAfangarBaekur>();
        vAfangarBaekur bok = new vAfangarBaekur();
        String bokHeiti = "Spurning ekki úr bók";
        if (!spurning.bok_id.equals("noBook")){
            baekur = vAfangarBaekur.getBokFromId(Integer.parseInt(spurning.bok_id));
            bok = baekur.get(0);
            bokHeiti=bok.getHeiti();
        };
        List<vKennariHoparOnn> vk = vKennariHoparOnn.getCourseList(Integer.parseInt(notandiID), Integer.parseInt(spurning.afangi_id));
        String edit=simpleDateFormat.format(spurning.getDagurstofnad());

        Question question = new Question(spurning.spurningar_id, "fjolval", spurning.texti, spurning.afangi_id, spurning.tyngdarstig,notandiID, now, bokHeiti, vk.get(0).getNamsgrein_afanganr());

        return ok(changeMultiChoiceQuestion.render(question, svor));//(questionForm,spurning));
    }

    public static Result changedMultiChoiceQuestion(){

        String[] spurningar_id = request().body().asFormUrlEncoded().get("spurningar_id");
        String[] changed_Question = request().body().asFormUrlEncoded().get("texti");
        String[] changed_right_answers = request().body().asFormUrlEncoded().get("svor_texti_rett");
        String[] changed_wrong_answers = request().body().asFormUrlEncoded().get("svor_texti_rangt");
        if(changed_Question!= null){
            Spurningar.changeQuestion(Integer.parseInt(spurningar_id[0]), changed_Question[0]);
        }
        if(changed_right_answers!=null||changed_wrong_answers!= null){
            Svor.changeMultiChoiceAnswers(Integer.parseInt(spurningar_id[0]), changed_right_answers, changed_wrong_answers);

        }
        return redirect(routes.TeacherController.questionBank());
    }
    public static Result teacherOpenAssignments(){
        String teacherID = session().get("notandiId");
        String nafn = session().get("nafn");
        if(!isTeacher(session().get("notandiId"))) {
            return redirect(routes.StudentController.studentDashboard());
        }

        List<verkefnihops> verkefniHops = verkefnihops.findProjectByTeacher(teacherID);  //get all the projects the teacher has created for its groups on the current semester
        List<Project> projects = new ArrayList<Project>();

        for(verkefnihops single:verkefniHops)   {

            Double grade = 20.0;
            Date lokadagsetning = single.lokadagsetning;
            Date upphafsdagsetning = single.upphafsdagsetning;
            Date today = new Date();
            //only projects that can still be turned in are shown on this dashboard (has to go into assignments to get the assignments that are closed)
            if(today.before(lokadagsetning)){
                String loka = simpleDateFormat.format(lokadagsetning);
                String upphafs = simpleDateFormat.format(upphafsdagsetning);
                Afangar afangi = Afangar.getAfangi(single.afangi_id);
                Verkefni verkefni = Verkefni.findProjectByVerkefniID(single.verkefni_id); //used to get the name of the project

                if(verkefni.tegund.equals("verkefni")){
                    projects.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,false,upphafs,loka,"verkefni",verkefni.verkefni_id,lokadagsetning,single.getHopur_id()));
                }
                else if(verkefni.tegund.equals("prof")){
                    projects.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,false,upphafs,loka,"prof",verkefni.verkefni_id,lokadagsetning,single.getHopur_id()));
                }
            }
        }

         return ok(teacherOpenAssignments.render(projects));
    }
}
